<template>
<div style="margin-top: 6px">
  <a-row :gutter="16">
  <a-col :span="6">
    <a-card title="文章列表" :bordered="false">
      <a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="搜索" />
      <a-directory-tree v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys"  :tree-data="treeData"
              defaultExpandAll="false" :autoExpandParent="false"
              @select="treeNodeClick" style="color: #40485b;"
      >
        <template #title="{ title }">
        <span v-if="title.toLowerCase().indexOf(searchValue.toLowerCase()) > -1">
          <span>{{title.substring(0, title.toLowerCase().indexOf(searchValue.toLowerCase()))}}</span>
          <span style="color: #f50">
            {{title.substring(title.toLowerCase().indexOf(searchValue.toLowerCase()),title.toLowerCase().indexOf(searchValue.toLowerCase())+searchValue.length)}}
          </span>
          <span>{{title.substring(title.toLowerCase().indexOf(searchValue.toLowerCase()) + searchValue.length)}}</span>
        </span>
          <span v-else>{{ title }}</span>
        </template>
        <template #switcherIcon="{expanded}">
          <folder-open-outlined v-if="expanded"/>
          <folder-outlined v-else/>
        </template>
        <template #icon="{ key, selected ,children,defaultIcon}">
          <file-outlined v-if="!children"/>
        </template>
      </a-directory-tree>
    </a-card>
  </a-col>
  <a-col :span="18">
    <a-row :gutter="16">
        <a-col :span="4" :xs="24" :sm="24" :lg="4">
          <div
              :style="{
            cursor: 'pointer',
            overflowY: 'scroll',
            padding: '5px',
            background:'#fff',
            boxSizing:'border-box',
            borderRadius: '2px',
            maxHeight: '800px',
            overflow: 'scroll'
          }"
          >
            <h3>内容导航</h3>
              <div v-for="item in catalogue"
                  :key="item"
                  class="list-group-item"
                  :style="{ padding: `10px 0 10px ${item.indent * 10}px` }"
                  @click="scrollTop(item)">
                  <a>{{ item.title }}</a>
              </div>
          </div>
        </a-col>
      <a-col :span="20" :xs="24"
             :sm="24"
             :md="16"
             :lg="20"
             :style="{
          height: sHeight,
          overflowY: 'scroll',
          background: '#ffffff'
        }"
             ref="scrollOut"
      >
        <h2 style="padding: 10px 32px;border-bottom: 2px solid #eee;">{{title}}</h2>
        <v-md-preview style="background:#ffffff" :text="messages" ref="preview" @copy-code-success="handleCopyCodeSuccess"></v-md-preview>
      </a-col>
    </a-row>
  </a-col>
  </a-row>
</div>
</template>

<script lang="ts" setup>
import { ref,nextTick } from 'vue';
import {getArticleList,getArticleTypeList} from "_apis/article";
import { FolderOpenOutlined,FolderOutlined,SmileOutlined,FileOutlined} from '@ant-design/icons-vue';
import {ArticleDataListResponse, ArticleTypeDataListResponse, GetArticleListRequest} from "_types/article"
import { message } from 'ant-design-vue';
import type { TreeProps } from 'ant-design-vue';
const messages = ref(""); // 文档内容
const catalogue: any = ref([]); // 目录列表
const sHeight = ref("100px");
const preview = ref();
const scrollOut = ref();
const expandedKeys = ref<string[]>(['1']);
const selectedKeys = ref<string[]>(['1-A1']);
const title = ref("")
const searchValue = ref<string>('');
const handleCopyCodeSuccess=(code:any)=>{
  navigator.clipboard.writeText(code);
  message.success("已复制到剪切板")
}
//创建目录
async function buildDirectory() {
  await nextTick();
  const anchors = preview.value.$el.querySelectorAll("h1,h2,h3,h4,h5,h6");

  const titles = Array.from(anchors).filter(
      (title: any) => !!title.innerText.trim()
  );

  if (!titles.length) {
    catalogue.value = [];
    return;
  }

  const hTags = Array.from(
      new Set(titles.map((title: any) => title.tagName))
  ).sort();

  catalogue.value = titles.map((el: any) => ({
    title: el.innerText,
    lineIndex: el.getAttribute("data-v-md-line"),
    indent: hTags.indexOf(el.tagName),
  }));
  sHeight.value = window.screen.height - 320 + "px";
}
//定位内容
// 定位内容
const scrollTop = (anchor: any) => {
  const { lineIndex } = anchor;
  const heading = preview.value.$el.querySelector(
      `[data-v-md-line="${lineIndex}"]`
  );
  if (heading) {
    console.log(preview.value);
    preview.value.scrollToTarget({
      target: heading,
      scrollContainer: scrollOut.value.$el,
      top: 0,
    });
  }
};
//分类
const treeData=ref<TreeProps['treeData']>([])

getArticleTypeList().then((res:ArticleTypeDataListResponse)=>{
  treeData.value = res.data;
})

const treeNodeClick=()=>{
  var value:string = selectedKeys.value.toString();
  let nodeKeys:string[] = value.split("-");
  if(nodeKeys.length>1){
   let nodeKey = nodeKeys[nodeKeys.length-1].replace("A","");
    const articleRequet:GetArticleListRequest={
      id:nodeKey+""
    }
    getArticleList(articleRequet).then((res:ArticleDataListResponse)=>{
      // 从接口获取文档内容，这部分省略了霍~
      messages.value = res.data?res.data.content:"";
      title.value = res.data?res.data.title:"";
      // 建目录
      buildDirectory()
    })
  }
}
treeNodeClick();
</script>

<style scoped>
/deep/ .ant-tree-switcher-noop {
  display:none;
}
.list-group-item a{
  color:#000
}
.list-group-item{
  font-size:13px;
  border-radius: 5px;
  list-style: none;
}
.list-group-item a{
  color: #40485b;
}
.list-group-item a::before {
  content: "\2022"; /* Unicode编码的圆点符号 */
  display: inline-block;
  font-weight: 800;
  margin-right: 5px;
}
/*.list-group-item:hover{*/
/*  background: #409eff78;*/
/*  color: #ffffff;*/
/*}*/
.list-group-item a:hover{
  color: #666666;
}
</style>
